<template>
  <div class="login">
    <el-form :model="UserForm" label-width="120px">
      <div class="login-img">
        <img src="@/assets/image/logo.png" alt="">
      </div>
      <div class="login-item">
        <div class="loginright">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="账号登录" name="first">
              <el-input v-model="UserForm.username" placeholder="请输入手机/用户名" />
              <el-input v-model="UserForm.password" type="password" placeholder="请输入密码" />
              <el-button type="primary" @click="onSubmit">登录</el-button>
              <p class="agreement">Design_by_zhangxing</p>
            </el-tab-pane>
            <el-tab-pane label="注册" name="second">
              <el-input v-model="UserForm.username" placeholder="请输入用户名" maxlength="10" />
              <el-input v-model="UserForm.password" type="password" placeholder="请输入密码" maxlength="8" />
              <el-input v-model="UserForm.password_sure" type="password" placeholder="请输入密码" maxlength="8" />
              <el-button type="primary" @click="onSubmit2">注册</el-button>
              <p class="agreement">Design_by_zhangxing</p>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-form>
  </div>

</template>

<script setup>
import "@/assets/css/login.css"
import axios from 'axios';
import { ref,reactive } from 'vue'
import {useRouter} from 'vue-router'
const router = useRouter();
const UserForm = reactive({
  username: '',
  password: '',
  password_sure: ''
})
const activeName = ref('first')
const onSubmit = async () => {
  try {
    const response = await axios.post('http://127.0.0.1:8000/user/api/login/', {
      username: UserForm.username,
      password: UserForm.password
    });
    localStorage.setItem('token', response.data.token);
    axios.defaults.headers.common['token']=localStorage.getItem('token');
    // 处理登录成功逻辑
    router.push('/index/interest');
  } catch (error) {
    console.error('登录失败', error);
    // 处理登录失败逻辑
  }
};

const onSubmit2 = async () => {
  // 简单的表单验证
  if (!UserForm.username || !UserForm.password) {
    alert('用户名和密码不能为空');
    return;
  }
  if (UserForm.password !== UserForm.password_sure) {
    alert('两次输入的密码不一致');
    return;
  }
  try {
    const response = await axios.post('http://127.0.0.1:8000/user/api/create/', {
      username: UserForm.username,
      password: UserForm.password,
    });
    if(response.data.msg === 'True') {
      alert('注册成功')
      router.push('/login');
    } else {
      alert(response.data.msg)
    }
  } catch (error) {
    console.error('注册失败', error);
    // 处理注册失败逻辑
  }
};
</script>

<style scoped>
/* 这里可以添加样式 */
</style>